//
//  IRTextView.m
//  us
//
//  Created by lhx on 2025/7/16.
//

#import "IRTextView.h"
#import "IRTextViewGestureRecognizer.h"

#define kTextControlViewSize 22
#define kTextMargin 15
#define kTextMinScale 0.5f
#define kTextMaxScale 3.5f

@interface IRTextView () <UIGestureRecognizerDelegate>

@property (strong, nonatomic) UIImageView *leftTopControl;
@property (strong, nonatomic) UIImageView *rightTopControl;
@property (strong, nonatomic) UIImageView *leftBottomControl;
@property (strong, nonatomic) UIImageView *rightBottomControl;
@property (strong, nonatomic) CAShapeLayer *shapeLayer;

@property (assign, nonatomic) BOOL enableLeftTopControl;
@property (assign, nonatomic) BOOL enableRightTopControl;
@property (assign, nonatomic) BOOL enableLeftBottomControl;
@property (assign, nonatomic) BOOL enableRightBottomControl;

@end

@implementation IRTextView

#pragma mark - Initial

- (instancetype)initWithContentFrame:(CGRect)frame{
    
    CGRect superRect = CGRectMake(frame.origin.x - kTextMargin, frame.origin.y - kTextMargin, frame.size.width + kTextMargin * 2, frame.size.height + kTextMargin * 2);
    
    self = [super initWithFrame:superRect];
    
    if (self) {
        
        self.contentTextView = [[UITextView alloc]initWithFrame:CGRectMake(kTextMargin, kTextMargin, frame.size.width, frame.size.height)];
        self.contentTextView.adjustsFontForContentSizeCategory = YES;
//        [self.contentTextView sizeToFit];
        self.contentTextView.backgroundColor = [UIColor clearColor];
        self.contentTextView.font = [UIFont systemFontOfSize:17];
        [self addSubview:self.contentTextView];
        
        @weakify(self);
        [[self.contentTextView.rac_textSignal takeUntil:self.rac_willDeallocSignal]
         subscribeNext:^(NSString * _Nullable text) {
            @strongify(self);

            // 拼音输入中不处理样式更新
//            UITextRange *markedRange = [self.contentTextView markedTextRange];
//            UITextPosition *pos = [self.contentTextView positionFromPosition:markedRange.start offset:0];
//            if (pos) return;

            [self setContentAttributeText:text];

        }];
        
        
        self.rightBottomControl = [[UIImageView alloc]init];
        self.rightBottomControl.image = [UIImage imageNamed:@"sticker_scale"];
        self.rightBottomControl.frame = CGRectMake(0, 0, kTextControlViewSize, kTextControlViewSize);
//        self.rightBottomControl.alpha = 0.65;
        
        [self addSubview:self.rightBottomControl];
    
        self.leftTopControl = [[UIImageView alloc]init];
        self.leftTopControl.image = [UIImage imageNamed:@"sticker_up"];
        self.leftTopControl.jk_size = CGSizeMake(kTextControlViewSize, kTextControlViewSize);
//        self.leftTopControl.alpha = 0.65;
        
        [self addSubview:self.leftTopControl];

        self.rightTopControl = [[UIImageView alloc]init];
        self.rightTopControl.image = [UIImage imageNamed:@"sticker_delete"];
        self.rightTopControl.jk_size = CGSizeMake(kTextControlViewSize, kTextControlViewSize);
//        self.rightTopControl.alpha = 0.65;
        
        [self addSubview:self.rightTopControl];
        
        
        self.leftBottomControl = [[UIImageView alloc]init];
        self.leftBottomControl.image = [UIImage imageNamed:@"sticker_down"];
        self.leftBottomControl.jk_size = CGSizeMake(kTextControlViewSize, kTextControlViewSize);
//        self.leftBottomControl.alpha = 0.65;
        [self addSubview:self.leftBottomControl];
        
        [self relocalControlView];
        
        [self setupConfig];
        [self attachGestures];
    }
    return self;
}

- (void)setContentAttributeText:(NSString *)text {
 
    self.contentTextView.text = text;
    // 自适应高度、
    
    CGSize size = [self.contentTextView sizeThatFits:CGSizeMake(self.jk_width, CGFLOAT_MAX)];
    
    self.contentTextView.jk_height = MAX(40, size.height);
    self.jk_height = MAX(40, size.height + kTextMargin * 2);
 
    [self relocalControlView];
    [self updateShapeLayer];

}
- (void)updateShapeLayer {
 

    CGRect shapeRect = self.contentTextView.bounds; // 使用 bounds 更准确
    self.shapeLayer.bounds = shapeRect;
    self.shapeLayer.position = CGPointMake(CGRectGetMidX(self.contentTextView.bounds),
                                       CGRectGetMidY(self.contentTextView.bounds));

    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, shapeRect);
    self.shapeLayer.path = path;
    CGPathRelease(path);
}

- (CAShapeLayer *)shapeLayer {
    if(_shapeLayer == nil) {
        _shapeLayer = [CAShapeLayer layer];
        
        [self.contentTextView.layer addSublayer:_shapeLayer];

        CGRect shapeRect = self.contentTextView.bounds;
        [_shapeLayer setBounds:shapeRect];
        [_shapeLayer setPosition:CGPointMake(self.contentTextView.frame.size.width / 2, self.contentTextView.frame.size.height / 2)];
        [_shapeLayer setFillColor:[[UIColor clearColor] CGColor]];
        [_shapeLayer setStrokeColor:[[UIColor brightBorderColor] CGColor]];
        [_shapeLayer setLineWidth:3];
    }
    return _shapeLayer;
}
 

- (void)setupConfig {
    self.exclusiveTouch = YES;
    
    self.userInteractionEnabled = YES;
    self.contentTextView.userInteractionEnabled = YES;
    self.rightBottomControl.userInteractionEnabled = YES;
    self.leftTopControl.userInteractionEnabled = YES;
    self.rightTopControl.userInteractionEnabled = YES;
    self.leftBottomControl.userInteractionEnabled = YES;
    
    _enableRightTopControl = NO;
    _enableLeftBottomControl = NO;
    _enableLeftTopControl = YES;
    _enableRightBottomControl = YES;
    self.enabledControl = YES;
    
    _enabledShakeAnimation = YES;
    self.enabledBorder = YES;
}

- (void)attachGestures {
    // ContentView
    UIRotationGestureRecognizer *rotateGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotate:)];
    [rotateGesture setDelegate:self];
    [self.contentTextView addGestureRecognizer:rotateGesture];
    
    UIPinchGestureRecognizer *pinGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handleScale:)];
    [pinGesture setDelegate:self];
    [self.contentTextView addGestureRecognizer:pinGesture];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleMove:)];
    [panGesture setMinimumNumberOfTouches:1];
    [panGesture setMaximumNumberOfTouches:2];
    [panGesture setDelegate:self];
    [self.contentTextView addGestureRecognizer:panGesture];
    
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [tapRecognizer setNumberOfTapsRequired:1];
    [tapRecognizer setDelegate:self];
    [self.contentTextView addGestureRecognizer:tapRecognizer];
    
    // DeleteControl
    UITapGestureRecognizer *tapRecognizer2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [tapRecognizer2 setNumberOfTapsRequired:1];
    [tapRecognizer2 setDelegate:self];
    [self.leftTopControl addGestureRecognizer:tapRecognizer2];
    
    // RightTopControl
    UITapGestureRecognizer *tapRecognizer3 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [tapRecognizer3 setNumberOfTapsRequired:1];
    [tapRecognizer3 setDelegate:self];
    [self.rightTopControl addGestureRecognizer:tapRecognizer3];
    
    // LeftBottomControl
    UITapGestureRecognizer *tapRecognizer4 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [tapRecognizer4 setNumberOfTapsRequired:1];
    [tapRecognizer4 setDelegate:self];
    [self.leftBottomControl addGestureRecognizer:tapRecognizer4];
    
    // ResizeControl
    IRTextViewGestureRecognizer *singleHandGesture = [[IRTextViewGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleHandAction:) anchorView:self.contentTextView];
    [self.rightBottomControl addGestureRecognizer:singleHandGesture];
    
    UITapGestureRecognizer *tapRecognizer5 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    [tapRecognizer5 setNumberOfTapsRequired:1];
    [tapRecognizer5 setDelegate:self];
    [self.rightBottomControl addGestureRecognizer:tapRecognizer5];
}

#pragma mark - Handle Gestures

- (void)handleTap:(UITapGestureRecognizer *)gesture {
    if (gesture.view == self.contentTextView) {
        [self handleTapContentView];
    } else if (gesture.view == self.leftTopControl) {
        if (_enableLeftTopControl) {
            if (_delegate && [_delegate respondsToSelector:@selector(ir_StickerViewDidTapLeftTopControl:)]) {
                [_delegate ir_StickerViewDidTapLeftTopControl:self];
            } else {
                // Default : remove from super view.
                [self removeFromSuperview];
            }
        }
    } else if (gesture.view == self.rightTopControl) {
        if (_enableRightTopControl) {
            if (_delegate && [_delegate respondsToSelector:@selector(ir_StickerViewDidTapRightTopControl:)]) {
                [_delegate ir_StickerViewDidTapRightTopControl:self];
            }
        }
    } else if (gesture.view == self.leftBottomControl) {
        if (_enableLeftBottomControl) {
            if (_delegate && [_delegate respondsToSelector:@selector(ir_StickerViewDidTapLeftBottomControl:)]) {
                [_delegate ir_StickerViewDidTapLeftBottomControl:self];
            }
        }
    } else if (gesture.view == self.rightBottomControl) {
        if (_enableRightBottomControl) {
            if (_delegate && [_delegate respondsToSelector:@selector(ir_StickerViewDidTapRightBottomControl:)]) {
                [_delegate ir_StickerViewDidTapRightBottomControl:self];
            }
        }
    }
}

- (void)handleTapContentView {
    [self.superview bringSubviewToFront:self];
    // Perform animation
    if (_enabledShakeAnimation) {
        [self performShakeAnimation:self];
    }
    if (_delegate && [_delegate respondsToSelector:@selector(ir_StickerViewDidTapContentView:)]) {
        [_delegate ir_StickerViewDidTapContentView:self];
    }
    
    [self.contentTextView becomeFirstResponder];
}

- (void)handleMove:(UIPanGestureRecognizer *)gesture {
    
    if ([self.superview isKindOfClass:[UIScrollView class]]) {
        
        UIScrollView *scollView = (UIScrollView *)self.superview;
        
        CGPoint translation = [gesture translationInView:scollView];
        // Boundary detection
        CGPoint targetPoint = CGPointMake(self.center.x + translation.x, self.center.y + translation.y);
        targetPoint.x = MAX(0, targetPoint.x);
        targetPoint.y = MAX(0, targetPoint.y);
        targetPoint.x = MIN(scollView.contentSize.width, targetPoint.x);
        targetPoint.y = MIN(scollView.contentSize.height, targetPoint.y);
        
        [self setCenter:targetPoint];
        [gesture setTranslation:CGPointZero inView:[self superview]];
        
    }else{
        
        CGPoint translation = [gesture translationInView:[self superview]];
        // Boundary detection
        CGPoint targetPoint = CGPointMake(self.center.x + translation.x, self.center.y + translation.y);
        targetPoint.x = MAX(0, targetPoint.x);
        targetPoint.y = MAX(0, targetPoint.y);
        targetPoint.x = MIN(self.superview.bounds.size.width, targetPoint.x);
        targetPoint.y = MIN(self.superview.bounds.size.height, targetPoint.y);
        
        [self setCenter:targetPoint];
        [gesture setTranslation:CGPointZero inView:[self superview]];
        
    }
    
}

- (void)handleScale:(UIPinchGestureRecognizer *)gesture {
    CGFloat scale = gesture.scale;
    // Scale limit
    CGFloat currentScale = [[self.contentTextView.layer valueForKeyPath:@"transform.scale"] floatValue];
    if (scale * currentScale <= kTextMinScale) {
        scale = kTextMinScale / currentScale;
    } else if (scale * currentScale >= kTextMaxScale) {
        scale = kTextMaxScale / currentScale;
    }

    self.contentTextView.transform = CGAffineTransformScale(self.contentTextView.transform, scale, scale);
    gesture.scale = 1;
    [self relocalControlView];
}

- (void)handleRotate:(UIRotationGestureRecognizer *)gesture {
    
    self.contentTextView.transform = CGAffineTransformRotate(self.contentTextView.transform, gesture.rotation);
    gesture.rotation = 0;
    [self relocalControlView];
    
}
- (void)handleSingleHandAction:(IRTextViewGestureRecognizer *)gesture {
    // 假设我们以 contentView 左上角为锚点
    CGPoint anchorPoint = self.contentTextView.frame.origin;

    // 当前手指位置是右下角控制点
    CGPoint currentTouch = gesture.currentTouchPoint;

    // 计算新的宽高
    CGFloat newWidth = currentTouch.x - anchorPoint.x;
    CGFloat newHeight = currentTouch.y - anchorPoint.y;

    // 限制最小尺寸
    newWidth = MAX(newWidth, 50);
    newHeight = MAX(newHeight, 50);

    // 更新 frame（左上角不变，宽高变化）
    CGRect newFrame = CGRectMake(anchorPoint.x, anchorPoint.y, newWidth, newHeight);
    self.contentTextView.frame = newFrame;

    // 更新控制点布局等
    [self relocalControlView];
    
    [self updateShapeLayer];
}


- (void)relocalControlView {
    
    CGPoint originalCenter = CGPointApplyAffineTransform(self.contentTextView.center, CGAffineTransformInvert(self.contentTextView.transform));
    
      self.rightBottomControl.center = CGPointApplyAffineTransform(CGPointMake(originalCenter.x + self.contentTextView.bounds.size.width / 2.0f, originalCenter.y + self.contentTextView.bounds.size.height / 2.0f), self.contentTextView.transform);
      self.leftTopControl.center = CGPointApplyAffineTransform(CGPointMake(originalCenter.x - self.contentTextView.bounds.size.width / 2.0f, originalCenter.y - self.contentTextView.bounds.size.height / 2.0f), self.contentTextView.transform);
      self.rightTopControl.center = CGPointApplyAffineTransform(CGPointMake(originalCenter.x + self.contentTextView.bounds.size.width / 2.0f, originalCenter.y - self.contentTextView.bounds.size.height / 2.0f), self.contentTextView.transform);
      self.leftBottomControl.center = CGPointApplyAffineTransform(CGPointMake(originalCenter.x - self.contentTextView.bounds.size.width / 2.0f, originalCenter.y + self.contentTextView.bounds.size.height / 2.0f), self.contentTextView.transform);
    
    CGFloat currentScale = [[self.contentTextView.layer valueForKeyPath:@"transform.scale"] floatValue];
    
//    [CATransaction begin];
//    [CATransaction setDisableActions:YES];
//    self.shapeLayer.lineWidth = 3/currentScale;
////    self.shapeLayer.lineDashPattern = @[@(3.f/currentScale),@(3.f/currentScale)];
//    [CATransaction commit];
    
}



#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.view == self.rightBottomControl && [gestureRecognizer isKindOfClass:[IRTextViewGestureRecognizer class]]) {
        if (_enableRightBottomControl) {
            if (_delegate && [_delegate respondsToSelector:@selector(ir_StickerViewDidTapRightBottomControl:)]) {
                [_delegate ir_StickerViewDidTapRightBottomControl:self];
                return NO;
            }
        }
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    
    return NO;
}




#pragma mark - Hit Test

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    if (self.hidden || !self.userInteractionEnabled || self.alpha < 0.01) {
        return nil;
    }
    if (_enabledControl) {
        if (_enableLeftTopControl && [self.leftTopControl pointInside:[self convertPoint:point toView:self.leftTopControl] withEvent:event]) {
            return self.leftTopControl;
        }
        if (_enableRightTopControl && [self.rightTopControl pointInside:[self convertPoint:point toView:self.rightTopControl] withEvent:event]) {
            return self.rightTopControl;
        }
        if (_enableLeftBottomControl && [self.leftBottomControl pointInside:[self convertPoint:point toView:self.leftBottomControl] withEvent:event]) {
            return self.leftBottomControl;
        }
        if (_enableRightBottomControl && [self.rightBottomControl pointInside:[self convertPoint:point toView:self.rightBottomControl] withEvent:event]) {
            return self.rightBottomControl;
        }
    }
    if ([self.contentTextView pointInside:[self convertPoint:point toView:self.contentTextView] withEvent:event]) {
        return self.contentTextView;
    }
    // return nil for other area.
    return nil;
}

#pragma mark - Other

- (void)performShakeAnimation:(UIView *)targetView {
    [targetView.layer removeAnimationForKey:@"anim"];
    CAKeyframeAnimation* animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.5f;
    animation.values = @[[NSValue valueWithCATransform3D:targetView.layer.transform],
                         [NSValue valueWithCATransform3D:CATransform3DScale(targetView.layer.transform, 1.05, 1.05, 1.0)],
                         [NSValue valueWithCATransform3D:CATransform3DScale(targetView.layer.transform, 0.95, 0.95, 1.0)],
                         [NSValue valueWithCATransform3D:targetView.layer.transform]
    ];
    animation.removedOnCompletion = YES;
    [targetView.layer addAnimation:animation forKey:@"anim"];
}

- (void)performTapOperation {
    [self handleTapContentView];
}

#pragma mark - Property

- (void)setDelegate:(id<IRTextViewDelegate>)delegate {
    if (delegate == nil) {
        NSAssert(delegate, @"Delegate shounldn't be nil!");
        return;
    }
    _delegate = delegate;
    
//    if ([_delegate respondsToSelector:@selector(ir_StickerView:imageForLeftTopControl:)]) {
//        UIImage *leftTopImage = [_delegate ir_StickerView:self imageForLeftTopControl:CGSizeMake(kTextControlViewSize, kTextControlViewSize)];
//        self.rightTopControl.image = leftTopImage;
//        if (leftTopImage) {
            _enableLeftTopControl = YES;
//        } else {
//            _enableLeftTopControl = NO;
//        }
//    }
//    if ([_delegate respondsToSelector:@selector(ir_StickerView:imageForRightTopControl:)]) {
//        UIImage *rightTopImage = [_delegate ir_StickerView:self imageForRightTopControl:CGSizeMake(kTextControlViewSize, kTextControlViewSize)];
//        self.rightTopControl.image = rightTopImage;
//        if (rightTopImage) {
            _enableRightTopControl = YES;
//        } else {
//            _enableRightTopControl = NO;
//        }
//    }
//    if ([_delegate respondsToSelector:@selector(ir_StickerView:imageForLeftBottomControl:)]) {
//        UIImage *leftBottomImage = [_delegate ir_StickerView:self imageForLeftBottomControl:CGSizeMake(kTextControlViewSize, kTextControlViewSize)];
//        self.leftBottomControl.image = leftBottomImage;
//        if (leftBottomImage) {
            _enableLeftBottomControl = YES;
//        } else {
//            _enableLeftBottomControl = NO;
//        }
//    }
//    if ([_delegate respondsToSelector:@selector(ir_StickerView:imageForRightBottomControl:)]) {
//        UIImage *rightBottomImage = [_delegate ir_StickerView:self imageForRightBottomControl:CGSizeMake(kTextControlViewSize, kTextControlViewSize)];
//        self.rightBottomControl.image = rightBottomImage;
//        if (rightBottomImage) {
            _enableRightBottomControl = YES;
//        } else {
//            _enableRightBottomControl = NO;
//        }
//    }
}

- (void)setEnabledControl:(BOOL)enabledControl {
    _enabledControl = enabledControl;
    self.leftTopControl.hidden = !_enabledControl;
    self.rightBottomControl.hidden = !_enabledControl;
    self.rightTopControl.hidden = !_enabledControl;
    self.leftBottomControl.hidden = !_enabledControl;
}

- (void)setEnabledBorder:(BOOL)enabledBorder {
    _enabledBorder = enabledBorder;
    if (_enabledBorder) {
        [self.contentTextView.layer addSublayer:self.shapeLayer];
    } else {
        [self.shapeLayer removeFromSuperlayer];
    }
}
 

@end
